package com.novasoftware.novagooglemap.service;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;

import com.novasoftware.NovaGoogleMapConfiguration;
import com.novasoftware.novagooglemap.db.DataBaseBuilder;
import com.novasoftware.novagooglemap.infrastructure.entity.BaseEntity;
import com.novasoftware.novagooglemap.infrastructure.util.Caller;
import com.novasoftware.novagooglemap.infrastructure.util.WSError;

public class JSONServiceBase<TEntity extends BaseEntity> {
	
	private DataBaseBuilder<TEntity> mBuilder;
	
	public JSONServiceBase(Activity activity,DataBaseBuilder<TEntity> builder)
	{
		mBuilder = builder;
	}
	
	public JSONArray searchJsonForEntity(String doGetString) throws JSONException {
		String jsonString = doGet(doGetString);
		JSONArray jsonArrayEntry = new JSONArray(jsonString); 
		return jsonArrayEntry;
	}
	
	public List<TEntity> getJSonList(String doGetString) throws JSONException,WSError{
		return getJsonList(searchJsonForEntity(doGetString));
	}
	
	public List<TEntity> getJsonList(JSONArray jsonArrayEntities) {
		
      int n = jsonArrayEntities.length();
		ArrayList<TEntity> entities = new ArrayList<TEntity>();
		
		for(int i=0; i < n; i++){
			try {
				entities.add(mBuilder.jsonBuild(jsonArrayEntities.getJSONObject(i)));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
        
		return entities;
	}

	public TEntity SaveJson(String doGetString,TEntity entity)
	{
		return null;
	}
	
	public List<TEntity> SaveJson(String doGetString,String jsonString)
	{
		return null;
	}
	public List<TEntity> SaveJsonList(String doGetString,List<TEntity> list)
	{
		return null;
	}
	
	public List<TEntity> SaveJsonList(String doGetString,String jsonString)
	{
		return null;
	}
	
	private String doGet(String query)
	{
		return Caller.doGet(NovaGoogleMapConfiguration.JSONServiceURL + query);
	}


}
